<?php

namespace App\Kuafu\Order\Command;

use App\Kuafu\CouponExt\Channel\CouponExtBase;
use App\Kuafu\CouponExt\Model\OrderCouponExtSplitModel;
use App\Library\FeiShu\SendFs;
use Illuminate\Console\Command;

class CalOrderCouponExtDue extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:calc-order-coupon-due';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '计算三方美团优惠券的手续费';

    /**
     * Create a new command instance.
     *
     * @return void//
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command
     *
     * @return int
     */
    public function handle()
    {
        try {
            $startTime = strtotime(date("Y-m-d", strtotime("-2 day")));
            $endTime   = $startTime + 24 * 60 * 60 - 1;

            for ($i = 0; $i <= 99; $i++) {
                $couponList = OrderCouponExtSplitModel::suffix($i)->query()
                                                      ->whereBetween('createdAt', [$startTime, $endTime])
                                                      ->where('couponStatus', 1)
                                                      ->where('fee', '<>', 0)
                                                      ->get()->toArray();

                foreach ($couponList as $coupon) {
                    $result = CouponExtBase::getIns($coupon['shopId'])->queryTradeDetail($coupon['couponCode']);
                    $data   = $result['data'][0] ?? [];
                    if (empty($data)) {
                        continue;
                    }
                    $update = [
                        'due' => bcmul($data['due'], 100),
                        'fee' => bcmul(bcsub($data['couponBuyPrice'], $data['due'], 2), 100)
                    ];
                    OrderCouponExtSplitModel::suffix($i)->where('id', $coupon['id'])->update($update);
                }
            }
        } catch (\Exception $exception) {
            SendFs::newRobot()->setTitleContent('[' . date('Y-m-d H:i:s') . '] : ' . 'Cal Order Coupon Ext Due 服务报错了',
                $exception)->send();
        }
    }
}
